/*
 * Copyright 2009 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kommando.web.opensearch.internal;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.kommando.core.osgi.BaseActivator;
import org.kommando.web.opensearch.actions.FindWithAction;
import org.kommando.web.opensearch.actions.SearchForAction;
import org.kommando.web.opensearch.objectsource.OpenSearch;
import org.kommando.web.opensearch.objectsource.OpenSearchObjectSource;
import org.osgi.framework.BundleContext;
import org.w3c.dom.Document;

/**
 * Activator for OpenSearch plugin.
 * 
 * @author Peter De Bruycker
 */
public class Activator extends BaseActivator {

    public void start(BundleContext context) throws Exception {
        OpenSearchObjectSource openSearchObjectSource = new OpenSearchObjectSource();

        registerObjectSource(context, openSearchObjectSource);

        // TODO move this to the object source?
        Enumeration<String> entryPaths = context.getBundle().getEntryPaths("/data");
        while (entryPaths.hasMoreElements()) {
            String plugin = entryPaths.nextElement();

            URL resource = context.getBundle().getResource(plugin);

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            try {
                InputStream inputStream = resource.openStream();
                Document document = documentBuilder.parse(inputStream);
                inputStream.close();

                OpenSearch openSearch = new OpenSearch(plugin, document);
                openSearchObjectSource.add(openSearch);
            } catch (IOException e) {
                // TODO log warning?
            }
        }

        registerAction(context, new FindWithAction());
        registerAction(context, new SearchForAction());
    }

    public void stop(BundleContext context) throws Exception {
    }

}
